package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.serve.dto.DeviceDto;
import com.zzyl.serve.vo.DeviceDetailVo;
import com.zzyl.serve.vo.DeviceReportDataVo;
import com.zzyl.serve.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 * 
 * @author Huanghc
 * @date 2025-08-22
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }

    @Override
    public void syncProductList() {

        ListProductsRequest request = new ListProductsRequest();
        ListProductsResponse response = client.listProducts(request);
        if(response.getHttpStatusCode()!=200){

            throw new BaseException("物联网接口-同步设备列表失败");
        }
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_KEY, JSONUtil.toJsonStr(response.getProducts()));



    }

    @Override
    public List<ProductVo> allProduct() {

      String srt = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);

        if(StringUtils.isEmpty(srt)){

            return Collections.emptyList();
        }
        return JSONUtil.toList(srt, ProductVo.class);

    }

    @Override
    public void addRegister(DeviceDto dto) {

        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery()
                .eq(dto.getNodeId() != null, Device::getNodeId, dto.getNodeId());
        Device device = getOne(wrapper);
        if (device != null) {
            throw new BaseException("设备标识码已存在，请重新输入");
        }
        wrapper = Wrappers.<Device>lambdaQuery().eq(StringUtils.isNotEmpty(dto.getDeviceName()), Device::getDeviceName, dto.getDeviceName());
        device = getOne(wrapper);
        if (device != null) {
            throw new BaseException("设备名称已存在，请重新输入");
        }
        wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getDeviceDescription, dto.getDeviceDescription())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType());
        device=getOne(wrapper);
        if(device!=null){
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withNodeId(dto.getNodeId());
        body.withDeviceName(dto.getDeviceName());
        body.withProductId(dto.productKey);

        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString(true);
        authInfo.withSecret(secret);
        body.setAuthInfo(authInfo);
        request.setBody(body);
        AddDeviceResponse response = client.addDevice(request);

        Device device1 = BeanUtil.toBean(dto, Device.class);

        device1.setIotId(response.getDeviceId());
        device1.setSecret(secret);
        save(device1);


    }

    @Override
    public DeviceDetailVo getInfo(String iotId) {

        //先从数据库中查
        LambdaQueryWrapper<Device> wrapper=Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId,iotId);
        Device device = getOne(wrapper);
        if(device==null){
            return null;
        }

        //再到华为云IOTDA中查询设备信息
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);

        DeviceDetailVo vo = new DeviceDetailVo();
        BeanUtils.copyProperties(device,vo);
        vo.setBindingLocation(Long.parseLong(device.getBindingLocation()));
        vo.setDeviceStatus(response.getStatus());
        String activeTime =response.getActiveTime();
        if(StringUtils.isNotEmpty(activeTime)){
            LocalDateTime dateTime=LocalDateTime.parse(activeTime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
            dateTime = dateTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            vo.setActiveTime(dateTime);
        }
        vo.setCreateTime(LocalDateTime.now());
        return vo;
    }

    @Override
    public List<DeviceReportDataVo> queryServiceProperties(String iotId) {


        //从华为云中拿信息
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        List<DeviceShadowData> shadow = response.getShadow();
        if(shadow==null||shadow.isEmpty()){
            return Collections.emptyList();
        }
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());

        String evenTimeStr = shadow.get(0).getReported().getEventTime();
        LocalDateTime dateTime = LocalDateTime.parse(evenTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"));
        LocalDateTime eveTime = dateTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();

        List<DeviceReportDataVo> list = new ArrayList<>();

        jsonObject.forEach((prop,value)->{

            DeviceReportDataVo vo = new DeviceReportDataVo();
            vo.setEventTime(eveTime);
            vo.setFunctionId(prop);
            vo.setValue(value);
            list.add(vo);
        });

        return list;
    }

    @Override
    public List<ServiceCapability> queryProduct(String productKey) {


        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse showProductResponse = client.showProduct(request);
        if(showProductResponse.getHttpStatusCode()!=200){
            throw new BaseException("物联网接口-查询产品信息失败");
        }

        return  showProductResponse.getServiceCapabilities();
    }

}
